<template>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left" class="form-container">
        <el-form-item label="姓名" prop="name" required>
            <el-input v-model="formData.name" placeholder="请输入姓名" class="w-[380px]" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="出生日期" prop="birth_date" required>
            <el-date-picker 
                v-model="formData.birth_date" 
                type="date" 
                placeholder="请选择出生日期"
                class="w-[380px]" 
                :disabled-date="disabledBirthDate"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
        </el-form-item>
        <el-form-item label="过世日期" prop="death_date" required>
            <el-date-picker 
                v-model="formData.death_date" 
                type="date" 
                placeholder="请选择过世日期"
                class="w-[380px]" 
                :disabled-date="disabledDeathDate"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
        </el-form-item>
        <el-form-item label="国籍" prop="nationality">
            <el-input v-model="formData.nationality" placeholder="请输入国籍" class="w-[380px]" maxlength="20" />
        </el-form-item>
        <el-form-item label="宗教" prop="religion">
            <el-input v-model="formData.religion" placeholder="请输入宗教信仰" class="w-[380px]" maxlength="20" />
        </el-form-item>
        <el-form-item label="情感关系" prop="relationship">
            <div class="w-[380px]">
                <el-select v-model="formData.relationship" clearable placeholder="请选择情感关系" style="width: 100%;">
                    <el-option v-for="item in props.relationshipList" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </div>
        </el-form-item>
        <el-form-item label="单人照" prop="photo">
            <el-upload
                class="avatar-uploader"
                :action="upLoadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
                <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <!-- <el-form-item label="墓碑寄语" prop="motto">
            <el-input 
                type="textarea" 
                :rows="3" 
                v-model="formData.motto" 
                placeholder="请输入墓碑寄语"
                class="w-[380px]" 
                maxlength="100"
                show-word-limit
            />
        </el-form-item> -->
        <!-- <el-form-item label="生平简介" prop="bio">
            <el-input 
                type="textarea" 
                rows="5" 
                v-model="formData.bio" 
                placeholder="请输入生平简介"
                class="w-[380px]" 
                maxlength="500"
                show-word-limit
            />
        </el-form-item> -->
        <el-form-item>
            <el-button type="primary" @click="submit" :loading="submitLoading">提交</el-button>
            <el-button @click="resetForm" :disabled="submitLoading">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile, type UploadFiles, type UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { apiMyMuEdit, apiMyMuDetail } from '@/api/graveyard'
import { useRoute } from 'vue-router'
import { defineProps } from 'vue'

const route = useRoute()

// 定义组件属性
const props = defineProps({
    relationshipList: {
        type: Array,
        default: () => [],
    },
    // 编辑模式下的初始数据
    initialData: {
        type: Object,
        default: () => ({}),
    },
    // 是否为编辑模式
    isEdit: {
        type: Boolean,
        default: false,
    },
    memorialId: {
        type: String,
        default: ''
    }
})

// 定义事件
const emit = defineEmits(['submit-success', 'submit-error'])

// 表单引用
const formRef = ref<FormInstance>()
const uploadRef = ref()

// 表单数据
const formData = ref({
    name: '',
    birth_date: '',
    death_date: '',
    avatar: '',
    relationship: '',
    religion: '',
    nationality: '中国',
    ancestral: '中国',
    career: '农民',
    alias: ''

    // name: '',
    // birth: '',
    // death: '',
    // nationality: '中国',
    // religion: '',
    // motto: '',
    // bio: '',
    // relationship: '',
    // photo: null as File | null,
})

    

// 文件列表
const fileList = ref<UploadFile[]>([])

// 提交状态
const submitLoading = ref(false)

// 表单验证规则
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z\s]+$/, message: '姓名只能包含中文、英文和空格', trigger: 'blur' }
    ],
    birth_date: [

        { required: true, message: '请选择出生日期', trigger: 'change' }
    ],
    death_date: [
        { required: true, message: '请选择过世日期', trigger: 'change' }
    ],
    nationality: [
        { max: 20, message: '国籍长度不能超过 20 个字符', trigger: 'blur' }
    ],
    religion: [
        { max: 20, message: '宗教信仰长度不能超过 20 个字符', trigger: 'blur' }
    ],
    motto: [
        { max: 100, message: '墓碑寄语长度不能超过 100 个字符', trigger: 'blur' }
    ],
    bio: [
        { max: 500, message: '生平简介长度不能超过 500 个字符', trigger: 'blur' }
    ]
})

// 日期禁用逻辑
const disabledBirthDate = (time: Date) => {
    const today = new Date()
    const deathDate = formData.value.death ? new Date(formData.value.death) : null
    
    // 出生日期不能晚于今天
    if (time.getTime() > today.getTime()) {
        return true
    }
    
    // 如果已选择过世日期，出生日期不能晚于过世日期
    if (deathDate && time.getTime() > deathDate.getTime()) {
        return true
    }
    
    return false
}

// 日期禁用逻辑2
const disabledDeathDate = (time: Date) => {
    const today = new Date()
    const birthDate = formData.value.birth ? new Date(formData.value.birth) : null
    
    // 过世日期不能晚于今天
    if (time.getTime() > today.getTime()) {
        return true
    }
    
    // 如果已选择出生日期，过世日期不能早于出生日期
    if (birthDate && time.getTime() < birthDate.getTime()) {
        return true
    }
    
    return false
}

// // 文件上传处理
// const beforePhotoUpload = (file: File) => {
//     const isImage = file.type.startsWith('image/')
//     const isLt2M = file.size / 1024 / 1024 < 2
    
//     if (!isImage) {
//         ElMessage.error('只能上传图片格式的文件！')
//         return false
//     }
//     if (!isLt2M) {
//         ElMessage.error('上传图片大小不能超过 2MB！')
//         return false
//     }
//     return true
// }
// // 图片上传
// const handlePhotoChange = (file: UploadFile, files: UploadFiles) => {
//     if (file.raw && beforePhotoUpload(file.raw)) {
//         formData.value.photo = file.raw
//         fileList.value = files
//     }
// }
// // 图片删除
// const handlePhotoRemove = () => {
//     formData.value.photo = null
//     fileList.value = []
// }

// 上传图片
const upLoadUrl = import.meta.env.VITE_APP_BASE_URL + '/api/upload/image'
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
    // formData.avatar = URL.createObjectURL(uploadFile.raw!)
    formData.avatar = response.data.uri || ''
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
    ElMessage.error('Avatar picture must be JPG、PNG、GIF format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 自定义日期验证
const validateDates = () => {
    if (formData.value.birth && formData.value.death) {
        const birthDate = new Date(formData.value.birth)
        const deathDate = new Date(formData.value.death)
        
        if (birthDate.getTime() >= deathDate.getTime()) {
            ElMessage.error('过世日期必须晚于出生日期')
            return false
        }
    }
    return true
}

// 提交表单
const submit = async () => {
    if (!formRef.value) return
    
    try {
        // 表单验证
        await formRef.value.validate()
        
        // 自定义日期验证
        if (!validateDates()) {
            return
        }
        
        submitLoading.value = true
        
        // 准备提交数据
        const formData = new FormData()
        
        // 添加表单字段
        Object.keys(formData.value).forEach(key => {
            if (key === 'photo') {
                if (formData.value.photo) {
                    formData.append('photo', formData.value.photo)
                }
            } else {
                const value = formData.value[key as keyof typeof formData.value]
                if (value !== null && value !== undefined && value !== '') {
                    formData.append(key, String(value))
                }
            }
        })
        
        // 调用API
        const response = await apiMyMuEdit(formData)
        
        if (response.code === 200) {
            ElMessage.success(props.isEdit ? '修改成功！' : '创建成功！')
            emit('submit-success', response.data)
            
            // 如果不是编辑模式，重置表单
            if (!props.isEdit) {
                resetForm()
            }
        } else {
            throw new Error(response.message || '提交失败')
        }
        
    } catch (error: any) {
        console.error('提交失败：', error)
        const errorMessage = error.message || '提交失败，请重试'
        ElMessage.error(errorMessage)
        emit('submit-error', error)
    } finally {
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    if (!formRef.value) return
    
    ElMessageBox.confirm(
        '确定要重置表单吗？这将清空所有已填写的内容。',
        '确认重置',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        formRef.value?.resetFields()
        formData.value = {
            name: '',
            birth: '',
            death: '',
            nationality: '中国',
            religion: '',
            motto: '',
            bio: '',
            relationship: '',
            photo: null,
        }
        fileList.value = []
        ElMessage.success('表单已重置')
    }).catch(() => {
        // 用户取消重置
    })
}

// 初始化表单数据（编辑模式）
const initFormData = () => {
    if (props.isEdit && props.initialData) {
        Object.keys(formData.value).forEach(key => {
            if (key in props.initialData && key !== 'photo') {
                (formData.value as any)[key] = props.initialData[key] || formData.value[key as keyof typeof formData.value]
            }
        })
        
        // 如果有初始图片，设置文件列表
        if (props.initialData.photoUrl) {
            fileList.value = [{
                name: 'photo',
                url: props.initialData.photoUrl,
                uid: Date.now(),
            }]
        }
    }
}

// 组件挂载时初始化
nextTick(() => {
    initFormData()
})

// 暴露方法给父组件
defineExpose({
    submit,
    resetForm,
    validate: () => formRef.value?.validate(),
    clearValidate: () => formRef.value?.clearValidate(),
})
</script>
<style scoped>
    .form-container {
        max-width: 1200px;
        margin: 30px auto;
        padding: 30px;
        border: 1px solid #e0e0e0;
        background-color: #fff;
        border-radius: 8px;
    }
</style>